package com.yao.controller;

import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.yao.dto.OrderDTO;
import com.yao.enums.ResultEnum;
import com.yao.exception.WeixinSellException;
import com.yao.service.OrderService;
import com.yao.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * User: 姚宏武
 * Date: 2017/11/22
 * Time: 16:23
 * Email：401369870@qq.com
 * Description: 微信支付
 */
@Controller
@Slf4j
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @Autowired
    private BestPayServiceImpl bestPayService;

    @GetMapping("/pay")
    public ModelAndView pay(@RequestParam("openid") String openid,
                            @RequestParam("orderId") String orderId,
                            @RequestParam("returnUrl") String returnUrl,
                            Map<String, Object> map) {

        // 1、查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new WeixinSellException(ResultEnum.ORDER_NOT_EXIST);
        }
        // 2、发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse", payResponse);

        try {
            returnUrl = java.net.URLDecoder.decode(returnUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("returnUrl", returnUrl);
        return new ModelAndView("pay/create", map);
    }

    @PostMapping(value = "/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);
        // 返回给微信处理结果，防止微信不停地发异步通知
        return new ModelAndView("pay/success");
    }

}
